package com.my.study.net;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Carlos
 * @version 1.0
 * @Description 接收方
 * @date 2021/7/4 15:03
 **/
@Slf4j(topic = "c.UDPReceiverA")
public class UDPReceiverA {

    public static void main(String[] args) throws IOException {
        // 创建一个DatagramSocket对象，准备在9999接收数据
        DatagramSocket socket = new DatagramSocket(9999);

        //================================================接收消息
        // 构建一个DatagramPacket对象，准备接收数据
        byte[] buf = new byte[1024];
        DatagramPacket packet = new DatagramPacket(buf, buf.length);
        // 接收，如果没有数据就会阻塞
        log.debug("A端，等待B端发送消息...");
        socket.receive(packet);
        // 拆包
        int length = packet.getLength();
        byte[] data = packet.getData();
        String s = new String(data, 0, length);
        log.debug("A端接收的消息: {}", s);


        //================================================发送消息
        byte[] sendMsg = "好滴，明天一起去海底捞吧".getBytes();
        DatagramPacket sendPacket = new DatagramPacket(sendMsg, 0, sendMsg.length, InetAddress.getByName("192.168.1.3"), 9998);
        log.debug("A端，回复B端...");
        socket.send(sendPacket);


        // 关闭资源
        socket.close();
    }

}
